<template>
  <div class="page">
    <hot-table
      ref="hotTable"
      :data="tableData"
      :settings="hotSettings"
      class="margin-top text-sm"
    ></hot-table>
    <!-- <div v-loading.fullscreen.lock="fullscreenLoading"></div> -->
  </div>
</template>

<script>
import { clone } from "@/utils/clone";
import { digitUppercase } from "@/utils";
import { HotTable } from "@handsontable/vue";
import Handsontable from "handsontable";
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import { m } from "@/store/yg/common/local";
import * as constant from "@/store/yg/common/constant";
import "handsontable/languages/zh-CN";
import "handsontable/dist/handsontable.full.css";
import globalData from "@/utils/config";
// import { log } from "console";
export default {
  components: {
    HotTable
  },
  props: {
    Constatvariable: {
      type: Object,
      default: function() {
        return {};
      }
    },
    templateData: {
      type: Array,
      default: function() {
        return [{}];
      }
    },
    options: {
      type: Array,
      default: function() {
        return [{}];
      }
    }
  },
  data() {
    return {
      tableData: [],
      fullscreenLoading: false,
      headerList: [
        "税务名称",
        "规格",
        "单位",
        "数量",
        "单价",
        "含税税额",
        "	税率",
        "税额",
        "操作"
      ],

      columns: [
        {
          data: "taxname", // 税务名称
          width: 160,
          type: "dropdown",
          source: (query, process) => {
            const list = [];
            for (const i of this.options) {
              list.push(i.taxName);
            }
            process(list);
          }
        },
        {
          data: "unitmeasure", // 	规格
          width: 60,
          readOnly: true,
          type: "text"
        },
        {
          data: "productmodel", // 单位
          width: 60,
          readOnly: true,
          type: "text" //
        },
        {
          data: "num", //数量
          width: 60,
          type: "text",
          validator: "numeric"
        },
        {
          data: "price", //单价
          // width: 60,
          type: "text",
          validator: "numeric"
        },
        {
          data: "ratetotal", //含税税额
          type: "text",
          validator: "numeric"
        },
        {
          data: "rate", // 税率
          // width: 80,
          readOnly: true,
          type: "text",
          validator: "numeric"
        },
        {
          data: "totalmoney", //	税额
          width: 160,
          readOnly: true,
          type: "text",
          validator: "numeric"
        },
        {
          readOnly: true,
          width: 60,
          renderer: this.coverRenderer
        }
      ]
    };
  },
  watch: {
    options: {
      deep: true,
      immediate: true,
      handler(val) {}
    },
    templateData: {
      handler(val) {
        if (val.length > 0 && this.tableData.length === 0) {
          this.tableData = [
            ...val,
            ...[
              { taxname: "合计：", ratetotal: 0, totalmoney: 0 },
              { taxname: "价税合计(大写)：", ratetotal: 0, totalmoney: 0 }
            ]
          ];

          this.calculateData(0);
          this.onCrop(0);
        } else if (val.length == 0 && this.tableData.length == 0) {
          this.$nextTick(() => {
            this.tableData = [
              {},
              { taxname: "合计：", ratetotal: 0, totalmoney: 0 },
              { taxname: "价税合计(大写)：", ratetotal: 0, totalmoney: 0 }
            ];
          });
        }
      }
      // deep: true,
      // immediate: true
    }
  },
  computed: {
    hotSettings() {
      return {
        currentRowClassName: "currentRow", // 为选中行添加类名，可以更改样式
        currentColClassName: "currentCol", // 为选中列添加类名
        stretchH: "all", // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: this.headerList,
        width: "100%",
        height: "200px",
        columns: this.columns,
        tableClassName: ["first-class-name", "second-class-name"],
        language: "zh-CN",
        mergeCells: this.mergeCells,
        cells: this.rowReadonly,
        beforeChange: (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
        },

        afterChange: (changes, source) => {
          //数据改变时触发此方法 捕捉数据更改
          if (!changes) return;
          const [row, prop, oldValue, newValue] = changes[0];
          console.log("prop :>> ", prop);
          if (prop === "taxname" && oldValue !== newValue) {
            const t = this.options.find(x => x.taxName === newValue);

            if (!t) return;
            this.$set(this.tableData[row], "num", 1);
            this.$set(
              this.tableData[row],
              "price",
              this.tableData[row].ratetotal
            );
            this.$set(this.tableData[row], "rate", t.taxRate);
            this.$set(this.tableData[row], "productmodel", t.productModel);
            this.$set(this.tableData[row], "unitmeasure", t.unitMeasure);
            this.$emit("changeCommdity", t.isPolicy);

            if (this.tableData[row].rate && this.tableData[row].ratetotal) {
              this.calculateData(row);
            }
          }
          if (
            (prop === "num" && this.tableData[row].price) ||
            (prop === "price" && this.tableData[row].num)
          ) {
            this.$set(
              this.tableData[row],
              "ratetotal",
              this.tableData[row].num * this.tableData[row].price
            );
            this.calculateData(row);
          }

          if (prop === "ratetotal" && this.tableData[row].num) {
            const price =
              (this.tableData[row].ratetotal * 100) /
              (this.tableData[row].num * 100);

            this.$delete(this.tableData[row], "price");
            this.$set(this.tableData[row], "price", price);
            this.calculateData(row);

            if (newValue > 99999.99) {
              this.onCrop(row);
            }
          }
        }
      };
    },
    mergeCells() {
      const l = this.tableData.length - 1;
      const l2 = this.tableData.length - 2;
      const arr = [];
      arr.push({ row: l, col: 0, rowspan: 1, colspan: 5 });
      arr.push({ row: l, col: 5, rowspan: 1, colspan: 2 });
      arr.push({ row: l, col: 7, rowspan: 1, colspan: 2 });
      arr.push({ row: l2, col: 0, rowspan: 1, colspan: 5 });
      arr.push({ row: l2, col: 5, rowspan: 1, colspan: 2 });
      arr.push({ row: l2, col: 7, rowspan: 1, colspan: 2 });

      // console.log("arr :>> ", arr);
      return arr;
    }
  },
  mounted() {
    // console.log("this.tableData :>> ", this.tableData);
  },
  methods: {
    calculateData(row) {
      // 税额
      // console.log("this.tableData[row].rate :>> ", this.tableData[row].rate);
      if (
        this.tableData[row].rate !== null &&
        this.tableData[row].rate !== undefined &&
        this.tableData[row].rate !== ""
      ) {
        const totalmoney =
          (this.tableData[row].ratetotal * (this.tableData[row].rate * 100)) /
          100;
        this.$set(this.tableData[row], "totalmoney", totalmoney.toFixed(2));
      }

      // 总税额T
      let totalTax = 0;
      // 总含税税额
      let includedTax = 0;

      const arr = this.tableData.slice(0, this.tableData.length - 2);

      for (const i of arr) {
        if (
          i.totalmoney !== null &&
          i.totalmoney !== undefined &&
          i.totalmoney !== ""
        ) {
          totalTax += parseFloat(i.totalmoney);
        }
        if (
          i.ratetotal !== null &&
          i.ratetotal !== undefined &&
          i.ratetotal !== ""
        ) {
          includedTax += parseFloat(i.ratetotal);
        }
      }
      this.$delete(this.tableData[this.tableData.length - 2], "ratetotal");
      this.$delete(this.tableData[this.tableData.length - 2], "totalmoney");
      this.$delete(this.tableData[this.tableData.length - 1], "ratetotal");
      this.$delete(this.tableData[this.tableData.length - 1], "totalmoney");
      this.$set(
        this.tableData[this.tableData.length - 2],
        "ratetotal",
        "￥" + includedTax
      );
      this.$set(
        this.tableData[this.tableData.length - 2],
        "totalmoney",
        "￥" + totalTax.toFixed(2)
      );
      this.$set(
        this.tableData[this.tableData.length - 1],
        "ratetotal",
        "￥" + digitUppercase(includedTax)
      );
      this.$set(
        this.tableData[this.tableData.length - 1],
        "totalmoney",
        "￥" + digitUppercase(totalTax.toFixed(2))
      );
      console.log("this.tableData :>> ", this.tableData);
      // this.$set(this.tableData[row], "ratetotal", includedTax);
    },
    rowReadonly(row, col, prop) {
      var cellProperties = {};
      if (row >= this.tableData.length - 2) {
        cellProperties.readOnly = true;
      }
      return cellProperties;
    },

    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      const l = this.tableData.length - 3;
      td.innerHTML = ``; // 清空单元格子集

      let btnCopy = document.createElement("i");

      btnCopy.onclick = params => {
        this.onCopy(row);
      };
      btnCopy.setAttribute(
        "class",
        "el-icon-circle-plus-outline margin-right-sm text-green"
      );

      td.appendChild(btnCopy); //添加按钮到单元格

      let btnDel = document.createElement("i");

      btnDel.setAttribute(
        "class",
        "el-icon-remove-outline margin-right-sm text-red"
      );
      btnDel.setAttribute("v-loading.fullscreen.lock", "fullscreenLoading");
      btnDel.onclick = params => {
        this.onDel(row);
      };

      td.appendChild(btnDel); //添加按钮到单元格

      if (row <= l && this.tableData[row].price > 99999.99) {
        let crop = document.createElement("i");

        crop.setAttribute(
          "class",
          "el-icon-scissors margin-right-sm text-blue"
        );
        crop.setAttribute("title", "裁剪");
        // crop.setAttribute("v-loading.fullscreen.lock", "fullscreenLoading");
        crop.onclick = params => {
          this.onCrop(row);
        };

        td.appendChild(crop); //添加按钮到单元格
      }

      return td;
    },
    onCrop(row) {
      const t = this.tableData[row].ratetotal;
      const p = 99999.99;

      if (t <= p) return;
      // 数量
      const sNum = Math.floor(t / 100000);
      //
      const secendPrice = ((t * 100 - sNum * p * 100) / 100).toFixed(2);

      // this.tableData[row].price = p;
      // this.tableData[row].num = sNum;
      // this.tableData[row].ratetotal = sNum * p;
      this.$set(this.tableData[row], "price", p);
      this.$set(this.tableData[row], "num", sNum);
      this.$set(this.tableData[row], "ratetotal", sNum * p);
      this.$set(
        this.tableData[row],
        "totalmoney",
        (sNum * p * this.tableData[row].rate).toFixed(2)
      );
      this.$nextTick(() => {
        this.tableData.splice(row + 1, 0, {
          taxname: this.tableData[row].taxname,
          unitmeasure: this.tableData[row].unitmeasure,
          productmodel: this.tableData[row].productmodel,
          price: secendPrice,
          num: 1,
          ratetotal: secendPrice,
          rate: this.tableData[row].rate,
          totalmoney: secendPrice * this.tableData[row].rate
        });
      });

      console.log("this.tableData[row] :>> ", this.tableData);
    },
    onDel(row) {
      if (this.tableData.length > 3) {
        this.tableData.splice(row, 1);
      }
    },
    onCopy(row) {
      this.tableData.splice(row + 1, 0, {});
    },

    checkRule(i) {
      if (!i.serCusId) {
        this.$message.error("请填写公司名");
        return false;
      } else if (!i.costName) {
        this.$message.error("请填写费用名称");
        return false;
      } else if (i.configPayTypec === "C3" && !i.responsibleId) {
        this.$message.error("请填写责任人");
        return false;
      } else if (!i.count) {
        this.$message.error("请填写数量");
        return false;
      } else if (!i.currency) {
        this.$message.error("请填写币种");
        return false;
      } else if (!i.unitPrice) {
        this.$message.error("请填写单价");
        return false;
      } else if (!i.billType) {
        this.$message.error("请填写账单类型");
        return false;
      }

      return true;
    }
  }
};
</script>

<style>
.page .ht_master .wtHolder {
  /* overflow-x: hidden; */
}
</style>
